﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using QW.Core;
using QW.Core.CommonModel;

namespace QW.Found.Filter
{
    public class ValidateModelFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                var validationErrors = modelState.Keys
                    .SelectMany(key => modelState[key].Errors.Select(x => new ValidationError(key, x.ErrorMessage)));
                var result = new CommonResult<List<ValidationError>>
                {
                    success = false,
                    code = (int)CommonResultCode.fail,
                    msg = "参数未能通过模型验证！",
                    data = validationErrors.ToList(),
                };
                context.Result = new ObjectResult(result);
            }
        }
    }

    public class ValidationError
    {
        public string Field
        {
            get; set;
        }

        public string Message
        {
            get; set;
        }

        public ValidationError(string field, string message)
        {
            Field = field;
            Message = message;
        }
    }
}
